/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Encripta.java
 *
 * Created on Sep 29, 2012, 3:20:33 PM
 */
package encriptador;

/**
 *
 * @author DAVID GATJENS
 */

import ensamble.*;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.*;
import javax.swing.JOptionPane;

public class Encripta extends javax.swing.JFrame {
    
    @Override
    public Image getIconImage(){
        Image refValue = Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("icons/PadLock-icon.png"));
        return refValue;
    }

    String key = "";
    String new_text;
    
    Diccionarios dic;
    
    /** Creates new form Encripta */
    public Encripta() {
        
        initComponents();
        
        this.setLocationRelativeTo(null);                
        
        dic = new Diccionarios();
        
        dic.llenar_primero();
        dic.llenar_segundo();
        dic.llenar_tercero();
        dic.llenar_cuarto();        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSlider1 = new javax.swing.JSlider();
        jfcLocation = new javax.swing.JFileChooser();
        bntEncriptar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txaTextoNormal = new javax.swing.JTextArea();
        lblIndicaciones = new javax.swing.JLabel();
        btnGenerar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(102, 153, 255));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setFont(new java.awt.Font("Franklin Gothic Book", 0, 14)); // NOI18N
        setIconImage(getIconImage());
        setName("Encriptador"); // NOI18N

        bntEncriptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/Actions-document-encrypt-icon.png"))); // NOI18N
        bntEncriptar.setText("Encriptar");
        bntEncriptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntEncriptarActionPerformed(evt);
            }
        });

        txaTextoNormal.setColumns(20);
        txaTextoNormal.setLineWrap(true);
        txaTextoNormal.setRows(5);
        jScrollPane2.setViewportView(txaTextoNormal);
        txaTextoNormal.setLineWrap(true);

        lblIndicaciones.setFont(new java.awt.Font("Vani", 1, 12)); // NOI18N
        lblIndicaciones.setText("Ingrese el texto que desea encriptar en el área de texto que se presenta acontinuación:");

        btnGenerar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/document-scroll-icon.png"))); // NOI18N
        btnGenerar.setText("Generar Archivo");
        btnGenerar.setEnabled(false);
        btnGenerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenerarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnGenerar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bntEncriptar, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblIndicaciones, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGap(30, 30, 30))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(lblIndicaciones)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bntEncriptar)
                    .addComponent(btnGenerar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bntEncriptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntEncriptarActionPerformed

        Properties bootstrap = new Properties();
        Activadores test = new Activadores();        
        boolean opposite_segment = false;
        int selectable_seed = 0;
        int get_lookup = 0;
        
        if (txaTextoNormal.getText().trim().equals("")){
            
            JOptionPane.showMessageDialog(null, "Debe ingresar un texto de longitud superior a 0 para continuar", "Inserción inválida", JOptionPane.WARNING_MESSAGE);
            txaTextoNormal.setText(null);
            txaTextoNormal.requestFocus();
            return;
            
        }
                
        String map [][] = null;
        File location = test.inicializar();
        String operand = "";
        String lookup_operand = "";        
        
        try {
            
            bootstrap.load(new FileInputStream(location.getAbsolutePath()));
                        
            int random = (int) (Integer.parseInt(bootstrap.getProperty("bls")) + (Math.random() * (Integer.parseInt(bootstrap.getProperty("bus")) - Integer.parseInt(bootstrap.getProperty("bls")))));
            
            if (random > 0 && random <= 50){
                
                operand = "-";
                key += "RS";
                
            }else if (random >= 51 && random <=100){
                
                operand = "+";
                key += "SR";
                
            }
            
            String dic_lookup;
            String sent_seed = "";
            
            int seed = (int) (Integer.parseInt(bootstrap.getProperty("ls")) + (Math.random() * (Integer.parseInt(bootstrap.getProperty("us")) - Integer.parseInt(bootstrap.getProperty("ls")))));
                       
            sent_seed = String.valueOf(seed);
            
            while (String.valueOf(seed).length() < Integer.parseInt(bootstrap.getProperty("sml"))){
                
                sent_seed = "0" + seed;
                
            }
            
            key += sent_seed;
            
            int next_lookup = (int) (Integer.parseInt(bootstrap.getProperty("bls")) + (Math.random() * (Integer.parseInt(bootstrap.getProperty("bus")) - Integer.parseInt(bootstrap.getProperty("bls")))));
            
            if (next_lookup > 0 && next_lookup <= 50){

                lookup_operand = "*";
                key += "ML";

            }else if (next_lookup >= 51 && next_lookup <=100){

                lookup_operand = "/";
                key += "DV";

            }
            
            String hex_parser = "";
            int random_lookup = (int) (Integer.parseInt(bootstrap.getProperty("lls")) + (Math.random() * (Integer.parseInt(bootstrap.getProperty("lus")) - Integer.parseInt(bootstrap.getProperty("lls")))));
            
            if (random_lookup > 0 && random_lookup <= 49){
                selectable_seed = 6;
            }else if (random_lookup >= 50 && random_lookup <= 99){
                selectable_seed = 9;
            }else if (random_lookup >= 100 && random_lookup <= 149){
                selectable_seed = 5;
            }else if (random_lookup >= 150 && random_lookup <= 199){
                selectable_seed = 8;
            }else if (random_lookup >= 200 && random_lookup <= 249){
                selectable_seed = 4;
            }else if (random_lookup >= 250 && random_lookup <= 300){
                selectable_seed = 7;
            }
            
            int index = 0;
            int bin_parser = 0;
            key += String.valueOf(selectable_seed);
            
            Conversores conversion = new Conversores();                    

            int selector = (int) (Integer.parseInt(bootstrap.getProperty("bls")) + (Math.random() * (Integer.parseInt(bootstrap.getProperty("bus")) - Integer.parseInt(bootstrap.getProperty("bls")))));                                        
            
            if (selector >= 0 && selector <=25){
                map = dic.diccionario(2);
                key += "02";
            }else if (selector >= 26 && selector <= 50){
                map = dic.diccionario(4);
                key += "04";
            }else if (selector >= 51 && selector <= 75){
                map = dic.diccionario(1);                    
                key += "01";
            }else if (selector >= 76 && selector <= 100){
                map = dic.diccionario(3);                    
                key += "03";
            }
                                                                            
            int range = 0;            
            new_text = "";            
            
            do{

                String target_lookup = "";
                int to_convert = (int) txaTextoNormal.getText().charAt(index);                
                
                switch (operand){
                    
                    case "+":
                        to_convert += seed;
                        break;
                    case "-":
                        to_convert -= seed;
                        break;
                        
                }
                
                if (to_convert < 0){
                    
                    opposite_segment = true;
                    to_convert = Math.abs(to_convert);
                    
                }                                
                
                bin_parser = conversion.toBin(to_convert);                
                hex_parser =  conversion.fromBin(bin_parser);   
                                                
                if (opposite_segment){
                    
                    hex_parser = "-" + hex_parser;
                    
                }                                                    
                
                try{
                    
                    get_lookup = Integer.parseInt(hex_parser);                                                                                                    
                    
                    if (get_lookup == 92 || get_lookup == 188 || get_lookup == -4){
                        
                        target_lookup = "\\";                        
                        
                    }else if (get_lookup == 127 || get_lookup == 223 || get_lookup == 31){
                        
                        target_lookup = "⌂";
                        
                    }else{
                        
                        target_lookup = bootstrap.getProperty(String.valueOf(get_lookup));
                        
                    }
                    
                }catch(NumberFormatException ex){
                    
                    get_lookup = conversion.toDec(hex_parser);
                    
                    if (get_lookup == 92 || get_lookup == 188 || get_lookup == -4){
                        
                        target_lookup = "\\";                        
                        
                    }else if (get_lookup == 127 || get_lookup == 223 || get_lookup == 31){
                        
                        target_lookup = "⌂";
                        
                    }else{
                        
                        target_lookup = bootstrap.getProperty(String.valueOf(get_lookup));
                        
                    }
                                        
                    for (int offset = 32; offset <= 127; offset++){
                    
                        if (bootstrap.getProperty(String.valueOf(offset)).equals(target_lookup)){
                            
                            get_lookup = offset;
                            break;                            
                        }
                        
                    }
                    
                }finally{
                    
                    switch (lookup_operand){
                        
                        case "*":
                            
                            get_lookup += selectable_seed;
                            break;
                            
                        case "/":
                            
                            get_lookup -= selectable_seed;
                            break;
                            
                    }                                       
                    
                    dic_lookup = bootstrap.getProperty(String.valueOf(get_lookup));
                    
                }
               
                boolean archieved = false;
                range = 0;
                
                while (archieved == false){
                    
                    if (map[0][range].equals(dic_lookup)){
                        
                        if (map[1][range].equals("blank")){

                            new_text += " ";
                            archieved = true;

                        }else if (map[1][range].equals("quote")){

                            new_text += "\"";
                            archieved = true;
                            
                        }else{

                            new_text += map[1][range];
                            archieved = true;

                        }                        
                        
                    }
                    
                    range++;
                    
                }
                
                index++;

            }while (index < txaTextoNormal.getText().length());
            
        } catch (IOException ex) {
            
            JOptionPane.showMessageDialog(null, ex.getMessage(),"Error al iniciar", JOptionPane.ERROR_MESSAGE);            
            
        }                                
        
        test.destuir(location);
        test.key(key);
        
        btnGenerar.setEnabled(true);
        
    }//GEN-LAST:event_bntEncriptarActionPerformed

    private void btnGenerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerarActionPerformed
        
        jfcLocation.showDialog(this, "Guardar");
        
        try{
            
            File destination = jfcLocation.getSelectedFile();
            OutputStream stream = new FileOutputStream(destination);
            Writer output = new OutputStreamWriter(stream);
            
            if (!destination.exists()){                
                
                output.write(new_text);

                output.close();
                
                JOptionPane.showMessageDialog(rootPane, "Archivo creado con éxito", "Operación Finalizada", JOptionPane.INFORMATION_MESSAGE);
                
            }else{
                
                int respuesta = JOptionPane.showConfirmDialog(rootPane, "El archivo existe, desea sobreescribirlo?", "Confirmar escritura", JOptionPane.WARNING_MESSAGE);
                
                if (respuesta == JOptionPane.YES_OPTION){
                    
                    output.write(new_text);
                    
                    output.close();
                    
                }
                
            }
                                    
        }catch (IOException ex){
            
            JOptionPane.showMessageDialog(rootPane, "No se puede escribir en la ruta especifada", "Error al escribir en disco", JOptionPane.ERROR_MESSAGE);
            
        }
        
    }//GEN-LAST:event_btnGenerarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Encripta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Encripta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Encripta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Encripta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Encripta().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bntEncriptar;
    private javax.swing.JButton btnGenerar;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSlider jSlider1;
    private javax.swing.JFileChooser jfcLocation;
    private javax.swing.JLabel lblIndicaciones;
    private javax.swing.JTextArea txaTextoNormal;
    // End of variables declaration//GEN-END:variables
}
